const fs = require("fs");
const NodeRSA = require('node-rsa');
module.exports = {
  //创建公/私密钥
  createKey: function () {
    //1.创建RSA对象，并指定 秘钥长度
    let key = new NodeRSA({ b: 1024 });
    key.setOptions({ encryptionScheme: 'pkcs1' });
    //2.生成 公钥私钥，使用 pkcs8标准，pem格式
    let publicPem = key.exportKey('pkcs8-public');
    let privatePem = key.exportKey('pkcs8-private');
    console.log('公钥:\n', publicPem);
    console.log('私钥:\n', privatePem);
  },
  //加密
  encrypt: (text) => {
    let _publicKey = fs.readFileSync("pem/pkcs8_public.pem");
    let key = new NodeRSA(_publicKey, 'pkcs8-public', { encryptionScheme: 'pkcs1' });
    let data = key.encrypt(text, 'base64');
    return data;
  },
  //解密
  decrypt: (ciphertext) => {
    let _privateKey = fs.readFileSync("pem/pkcs8_private.pem");
    let key = new NodeRSA(_privateKey, 'pkcs8-private', { encryptionScheme: 'pkcs1' });
    let data = key.decrypt(ciphertext, 'utf8');
    return data;
  }
}